package com.tuo51.partner.controller;


import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.core.service.StaffService;
import com.tuo51.evaluate.domain.childrens.Children;
import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Record;
import com.tuo51.evaluate.service.ChildrenService;
import com.tuo51.evaluate.service.EvaluateV2Service;
import com.tuo51.evaluate.vo.children.ChildrenExtendInfoVO;
import com.tuo51.evaluate.vo.children.ChildrenVO;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.foudation.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import static com.tuo51.foudation.constant.RequestConstant.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 测评小程序使用的接口
 */

@RestController
@RequestMapping("/partner/family")
@Api(value = "/partner/family", tags = "伙伴接口 - 家长")
public class PartnerFamilyController {

    @Autowired
    private EvaluateV2Service evaluateService;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private StaffService staffService;

    @Value("${export.pb.share_url_ma}")
    private String exportShareURLMA;

    @Value("${export.pb.share_url_mp}")
    private String exportShareURLMP;

//    1. 家长信息同步：
//            1.1 家长信息新增；（需要返回你们数据库表唯一区分的家长id）
//            1.2 家长信息修改；
//            1.4 家长信息查询（至少需要可通过家长id，家长姓名，家长手机进行筛选）
//            1.5 家长详情获取（通过家长id带出完整信息，如果家长查询信息里面已经是完整的，则可忽略）
//
//            2. 家长幼儿信息同步：
//            2.1 家长幼儿信息新增；（需要返回你们数据库表唯一区分的家长幼儿id）
//            2.2 家长幼儿信息修改；
//            2.3 家长幼儿信息删除；
//            2.4 家长幼儿信息查询；（至少需要可通过家长id，幼儿id，幼儿姓名，家长姓名，家长手机进行筛选）
//            2.5 家长设置默认幼儿信息；（通过家长id和幼儿id建立默认绑定关系）
//            2.6 家长获取默认幼儿信息；（通过家长id获取已绑定默认关系的幼儿信息）
//
//            6. 家长对订单点击查看测评报告，跳转到你们测评报告的方式（家长订单跟你们的测试报告id建立关系后，家长点击查看报告，
//                  可以携带你们的报告id进入测评系统查看报告）

    @RequestMapping(value = "/report_shared_url", method = GET)
    @ApiOperation(value = "分享链接，获取到的链接没有权限限制，可任意访问")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "partner", value = "伙伴 id，测评师为 express", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "uuid", value = "随机生成的 uuid，用以防重复提交放反推", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "compver", value = "组件版本，当前为 1", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "auth", value = "签名，签名算法见范例", required = true, dataType = "string"),
            @ApiImplicitParam(name = "pUserId", value = "伙伴侧用户id，长度32，（/wx/user/{appid}/login 接口获取）", required = true, dataType = "string"),
            @ApiImplicitParam(name = "reportId", value = "报告id，长度32，（/partner/org/add_evaluate 接口获取）", required = true, dataType = "string")
    })
    public StatusResponse sharedUrlOfReport(@RequestHeader(PARTNERID_KEY) String partner,
                                            @RequestHeader(AUTH_KEY) String auth,
                                            @RequestHeader(REQ_UUID_KEY) String uuid,
                                            @RequestHeader(COMP_VERSION_KEY) String compver,
                                            String pUserId,
                                            String reportId) {

        Staff staff = staffService.mpUserByPartnerUserId(pUserId);
        if (staff == null){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "用户不存在");
        }

        EvaluateV2Record evaluateRecord = evaluateService.getEvaluateDetail(reportId);

        Map result = new HashMap();

        result.put("url_mp", exportShareURLMP + "?id=" + evaluateRecord.getId());
        result.put("url_ma", exportShareURLMA + "?id=" + evaluateRecord.getId());
        result.put("childrenName", evaluateRecord.getChildrenName());
        result.put("month", evaluateRecord.getMonth());

        return StatusResponse.success(result);
    }

    @RequestMapping(value = "/mychildren", method = POST)
    @ApiOperation(value = "获取用户宝宝列表, 响应对象内 ref：指用户通过手机绑定关联的宝宝，my：指用户所拥有的宝宝， default：指用户在公众号内设定的默认宝宝")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "partner", value = "伙伴 id，测评师为 express", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "uuid", value = "随机生成的 uuid，用以防重复提交放反推", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "compver", value = "组件版本，当前为 1", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "auth", value = "签名，签名算法见范例", required = true, dataType = "string"),
            @ApiImplicitParam(name = "pUserId", value = "伙伴侧用户id，长度32，（/wx/user/{appid}/login 接口获取）", required = true, dataType = "string")
    })
    public StatusResponse getChildren(@RequestHeader(PARTNERID_KEY) String partner,
                                      @RequestHeader(AUTH_KEY) String auth,
                                      @RequestHeader(REQ_UUID_KEY) String uuid,
                                      @RequestHeader(COMP_VERSION_KEY) String compver,
                                      String pUserId){

        Staff staff = staffService.mpUserByPartnerUserId(pUserId);

        Object ret = childrenService.getAllWithSourceByParent(staff);

        return StatusResponse.success(ret);
    }

    @RequestMapping(value = "/child_detail", method = POST)
    @ApiOperation(value = "获取用户宝宝详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "partner", value = "伙伴 id，测评师为 express", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "uuid", value = "随机生成的 uuid，用以防重复提交放反推", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "compver", value = "组件版本，当前为 1", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "auth", value = "签名，签名算法见范例", required = true, dataType = "string"),
            @ApiImplicitParam(name = "pUserId", value = "伙伴侧用户id，长度32，（/wx/user/{appid}/login 接口获取）", required = true, dataType = "string"),
            @ApiImplicitParam(name = "childrenId", value = "宝宝id，长度32，（/partner/org/mychildren 接口获取）", required = true, dataType = "string")
    })
    public StatusResponse childDetail(@RequestHeader(PARTNERID_KEY) String partner,
                                      @RequestHeader(AUTH_KEY) String auth,
                                      @RequestHeader(REQ_UUID_KEY) String uuid,
                                      @RequestHeader(COMP_VERSION_KEY) String compver,
                                      String pUserId, String childrenId){

        Staff staff = staffService.mpUserByPartnerUserId(pUserId);

        Children children = childrenService.getById(childrenId, staff.getId());

        return StatusResponse.success(ChildrenVO.of(children));
    }

    @RequestMapping(value = "/delete", method = POST)
    @ApiOperation(value = "删除宝宝，仅能删除用户所拥有的宝宝")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "partner", value = "伙伴 id，测评师为 express", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "uuid", value = "随机生成的 uuid，用以防重复提交放反推", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "compver", value = "组件版本，当前为 1", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "auth", value = "签名，签名算法见范例", required = true, dataType = "string"),
            @ApiImplicitParam(name = "pUserId", value = "伙伴侧用户id，长度32，（/wx/user/{appid}/login 接口获取）", required = true, dataType = "string"),
            @ApiImplicitParam(name = "childrenId", value = "宝宝id，长度32，（/partner/org/mychildren 接口获取）", required = true, dataType = "string")
    })
    public StatusResponse deleteChildren(@RequestHeader(PARTNERID_KEY) String partner,
                                         @RequestHeader(AUTH_KEY) String auth,
                                         @RequestHeader(REQ_UUID_KEY) String uuid,
                                         @RequestHeader(COMP_VERSION_KEY) String compver,
                                         String pUserId, String childrenId) {

        Staff staff = staffService.mpUserByPartnerUserId(pUserId);

        if (staff == null){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "用户不存在");
        }

        boolean ret = childrenService.deleteChildrenForStaff(childrenId, staff.getId());

        return StatusResponse.success(ret);
    }

    @ApiOperation("更新宝宝信息，所有字段可选")
    @RequestMapping(value = "/update_child_info", method = POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "partner", value = "伙伴 id，测评师为 express", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "uuid", value = "随机生成的 uuid，用以防重复提交放反推", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "compver", value = "组件版本，当前为 1", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "auth", value = "签名，签名算法见范例", required = true, dataType = "string"),
            @ApiImplicitParam(name = "pUserId", value = "伙伴侧用户id，长度32，（/wx/user/{appid}/login 接口获取）", required = true, dataType = "string"),
            @ApiImplicitParam(name = "childrenId", value = "宝宝id，长度32，（/partner/org/mychildren 接口获取）", required = true, dataType = "string"),
            @ApiImplicitParam(name = "childrenName", value = "宝宝姓名，长度50", required = false, dataType = "string"),
            @ApiImplicitParam(name = "nickName", value = "宝宝昵称，长度50", required = false, dataType = "string"),
            @ApiImplicitParam(name = "avatar", value = "宝宝头像URL，长度512", required = false, dataType = "string"),
            @ApiImplicitParam(name = "gender", value = "宝宝性别 ：0：女，1：男", required = false, dataType = "int"),
            @ApiImplicitParam(name = "birthday", value = "生日， 如 2018-08-08  或 2018/08/08 或 2018年08月08日", required = false, dataType = "string"),
            @ApiImplicitParam(name = "guardianPhone", value = "监护人电话，长度32", required = false, dataType = "string"),
            @ApiImplicitParam(name = "guardianName", value = "监护人姓名,长度32", required = false, dataType = "string"),
            @ApiImplicitParam(name = "guardianRelation", value = "监护人关系，长度32", required = false, dataType = "string"),
            @ApiImplicitParam(name = "householdType", value = "户籍类型,长度32", required = false, dataType = "string"),
            @ApiImplicitParam(name = "identityCard", value = "身份证/出生证字段，长度32", required = false, dataType = "string"),
            @ApiImplicitParam(name = "goodLanguageDesc", value = "擅长语言，长度500", required = false, dataType = "string"),
            @ApiImplicitParam(name = "weight", value = "体重，可浮点化", required = false, dataType = "string"),
            @ApiImplicitParam(name = "height", value = "身高，可浮点化", required = false, dataType = "string"),
            @ApiImplicitParam(name = "header", value = "头围，可浮点化", required = false, dataType = "string"),
            @ApiImplicitParam(name = "address", value = "地址，长度256", required = false, dataType = "string"),
            @ApiImplicitParam(name = "remark", value = "备注，长度500", required = false, dataType = "string")
    })
    public StatusResponse updateChildInfo(@RequestHeader(PARTNERID_KEY) String partner,
                                          @RequestHeader(AUTH_KEY) String auth,
                                          @RequestHeader(REQ_UUID_KEY) String uuid,
                                          @RequestHeader(COMP_VERSION_KEY) String compver,
                                          String pUserId,
                                          String childrenId,
                                          String childrenName,
                                          String nickName,
                                          String avatar,
                                          Integer gender,
                                          String birthday,
                                          String guardianPhone, String guardianName, String guardianRelation,
                                          String householdType, String identityCard, String goodLanguageDesc,//户籍类型：householdType、身份证/出生证字段: identityCard;、擅长语言描述: goodLanguageDesc
                                          String weight,
                                          String height,
                                          String header,
                                          String address,
                                          String remark){

        Staff staff = staffService.mpUserByPartnerUserId(pUserId);

        if (staff == null){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "用户不存在");
        }

        if (StringUtils.isEmpty(childrenId)){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        }

        Children children = childrenService.getById(childrenId, staff.getId());
        if (children == null){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        }

        ChildrenVO vo = new ChildrenVO();
        ChildrenExtendInfoVO extendInfoVO = new ChildrenExtendInfoVO();
        vo.setExtendInfo(extendInfoVO);

        vo.setName(childrenName);
        vo.setNickName(nickName);
        vo.setImgUrl(avatar);

        //birthday, gender, weight, height, header, address, remark
        if (StringUtils.isNotEmpty(birthday))
            vo.setBirthday(DateUtil.parseToDate(birthday));

        vo.setGender(gender);
        vo.setWeight(weight);
        vo.setHeight(height);
        vo.setHeader(header);
        vo.setRemark(remark);

        extendInfoVO.setGuardianName(guardianName);
        extendInfoVO.setGuardianPhone(guardianPhone);
        extendInfoVO.setGuardianRelation(guardianRelation);
        extendInfoVO.setGoodLanguageDesc(goodLanguageDesc);
        extendInfoVO.setIdentityCard(identityCard);
        extendInfoVO.setHouseholdType(householdType);

        extendInfoVO.setAddress(address);

        children = childrenService.edit(children, vo);

        return StatusResponse.success(ChildrenVO.of(children));
    }


    @ApiOperation("新建宝宝，创建在服务号对应的用户对象下")
    @RequestMapping(value = "/add_children", method = POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "partner", value = "伙伴 id，测评师为 express", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "uuid", value = "随机生成的 uuid，用以防重复提交放反推", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "compver", value = "组件版本，当前为 1", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "auth", value = "签名，签名算法见范例", required = true, dataType = "string"),
            @ApiImplicitParam(name = "pUserId", value = "伙伴侧用户id，长度32，（/wx/user/{appid}/login 接口获取）", required = true, dataType = "string"),

            @ApiImplicitParam(name = "childrenName", value = "宝宝姓名，长度50", required = true, dataType = "string"),
            @ApiImplicitParam(name = "nickName", value = "宝宝昵称，长度50", required = true, dataType = "string"),
            @ApiImplicitParam(name = "childAvatarUrl", value = "宝宝头像URL，长度512", required = false, dataType = "string"),
            @ApiImplicitParam(name = "gender", value = "宝宝性别 ：0：女，1：男", required = true, dataType = "int"),
            @ApiImplicitParam(name = "birthday", value = "生日， 如 2018-08-08  或 2018/08/08 或 2018年08月08日", required = true, dataType = "string"),
            @ApiImplicitParam(name = "guardianPhone", value = "监护人电话，长度32", required = false, dataType = "string"),
            @ApiImplicitParam(name = "guardianName", value = "监护人姓名,长度32", required = false, dataType = "string"),
            @ApiImplicitParam(name = "guardianRelation", value = "监护人关系，长度32", required = false, dataType = "string"),
            @ApiImplicitParam(name = "householdType", value = "户籍类型,长度32", required = false, dataType = "string"),
            @ApiImplicitParam(name = "identityCard", value = "身份证/出生证字段，长度32", required = false, dataType = "string"),
            @ApiImplicitParam(name = "goodLanguageDesc", value = "擅长语言，长度500", required = false, dataType = "string"),
            @ApiImplicitParam(name = "weight", value = "体重，可浮点化", required = false, dataType = "string"),
            @ApiImplicitParam(name = "height", value = "身高，可浮点化", required = false, dataType = "string"),
            @ApiImplicitParam(name = "header", value = "头围，可浮点化", required = false, dataType = "string"),
            @ApiImplicitParam(name = "address", value = "地址，长度256", required = false, dataType = "string"),
            @ApiImplicitParam(name = "remark", value = "备注，长度500", required = false, dataType = "string")
    })
    public StatusResponse addChildren(@RequestHeader(PARTNERID_KEY) String partner,
                                      @RequestHeader(AUTH_KEY) String auth,
                                      @RequestHeader(REQ_UUID_KEY) String uuid,
                                      @RequestHeader(COMP_VERSION_KEY) String compver,
                                      String pUserId,
                                      String childAvatarUrl,
                                      String childrenName,
                                      String nickName,
                                      Integer gender,
                                      String birthday,
                                      String guardianPhone, String guardianName, String guardianRelation,
                                      String householdType, String identityCard, String goodLanguageDesc,//户籍类型：householdType、身份证/出生证字段: identityCard;、擅长语言描述: goodLanguageDesc
                                      String weight, String height,
                                      String header,
                                      String address,
                                      String remark){

        Staff staff = staffService.mpUserByPartnerUserId(pUserId);

        ChildrenVO vo = new ChildrenVO();
        ChildrenExtendInfoVO extendInfoVO = new ChildrenExtendInfoVO();
        vo.setExtendInfo(extendInfoVO);

        vo.setStaffId(staff.getId());

        vo.setImgUrl(childAvatarUrl);
        vo.setName(childrenName);
        vo.setNickName(nickName);

        //birthday, gender, weight, height, header, address, remark
        if (StringUtils.isNotEmpty(birthday))
            vo.setBirthday(DateUtil.parseToDate(birthday));

        vo.setGender(gender);
        vo.setWeight(weight);
        vo.setHeight(height);
        vo.setHeader(header);
        vo.setRemark(remark);

        extendInfoVO.setAddress(address);

        extendInfoVO.setGuardianName(guardianName);
        extendInfoVO.setGuardianPhone(guardianPhone);
        extendInfoVO.setGuardianRelation(guardianRelation);
        extendInfoVO.setGoodLanguageDesc(goodLanguageDesc);
        extendInfoVO.setIdentityCard(identityCard);
        extendInfoVO.setHouseholdType(householdType);

        Children children = childrenService.add(vo);

        return StatusResponse.success(ChildrenVO.of(children));

    }
}
